#include "Socket.hpp"
#include "Common.hpp"
#include <iostream>
#include <string>
#include <memory>
#include "Protocol.hpp"

using namespace SocketModule;

void GetDataFromStdin(int &x, int &y, char &oper)
{
    std::cout << "Please input x, y, oper(+-*/): ";
    std::cin >> x >> y >> oper;
}

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " <server_ip> <server_port>" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuidTcpClientSocketMethod();

    if (client->Connect(server_ip, server_port) != 0)
    {
        std::cerr << "Connect failed." << std::endl;
        exit(CONNECT_ERR);
    }

    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    std::string resp_buffer;
    // 连接服务器成功
    while (true)
    {
        std::string req_str;
        int cnt = 3;
        while (cnt--)
        {
            int x, y;
            char oper;
            GetDataFromStdin(x, y, oper);

            // 构建一个请求-> 可以直接发送的字符串
            req_str += protocol->BuildRequestString(x, y, oper);
            std::cout << "------------encode req string-------------" << std::endl;
            std::cout << req_str << std::endl;
            std::cout << "------------------------------------------" << std::endl;
        }

        // 发送请求
        client->Send(req_str);

        // 获取应答
        Response resp;
        bool res = protocol->GetResponse(client, resp_buffer, &resp);
        if (res == false)
            break;
        // resp.ShowResult();
    }
    return 0;
}